#!/usr/bin/env python
# encoding: utf-8
'''
@author: 王震
@license: 四川凡狼科技有限公司
@contact: 2668985108@qq.com
@file: note.py
@time: 2021/10/2 2:58 下午
@desc:
'''
from main import db
from app.public.sqlMethods import existence
from app.model.note.note import Note
from app.model.classHour.classHour import ClassHour
from app.msg.tips import tipsText, tips
from app.msg.resp import response_json
from app.public.tool import create_key
from app.serialize.note import Note as NoteObj
from app.public.sqlMethods import auto_commit_db


def add_note(data):
    obj = {
        'details': '',
        'parentId': ""
    }
    if existence(obj=data, target=obj):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    with auto_commit_db():
        res = ClassHour.query.filter_by(id=data['parentId']).count()
        if not res:
            return response_json(code=tips['noResult'], msg=tipsText['noResult'])
        res = Note.query.filter_by(parentId=data['parentId']).count()
        note = Note()
        if res:
            Note.query.filter_by(parentId=data['parentId']).update(data)
        else:
            for key in data:
                setattr(note, key, data[key]) if hasattr(note, key) and data[key] else None
            note.id = create_key()
            db.session.add(note)
    return response_json()


def get_note_details(_id):
    obj = {
        'parentId': ""
    }
    if existence(obj={'parentId': _id}, target=obj):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    with auto_commit_db():
        res = Note.query.filter_by(parentId=_id).first()
        if not res:
            return response_json(code=tips['noResult'], msg=tipsText['noResult'])
        note_obj = NoteObj()
        data = note_obj.dump(res)
    return response_json(data=data)
